<template>
  <div class="login-container">
    <div class="login-form-content">
      <div class="login-bg">
        <div class="header s-d-flex s-jc-space-between s-ai-center">
          <div class="flex-1 fz20 title">申请注册</div>
          <div class="flex-1 back s-pointer s-tar" @click="backLogin">返回登录</div>
        </div>
        <div>
          <a-form
            ref="formRef"
            :model="formState"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            style="display: flex; flex-wrap: wrap"
          >
            <div class="sub-title mt29 mb30">个人信息</div>
            <a-form-item
              style="width: 100%"
              ref="adminName"
              label="管理员姓名"
              name="adminName"
            >
              <a-input
                v-model:value="formState.adminName"
                placeholder="请输入管理员姓名"
              />
            </a-form-item>
            <a-form-item
              style="width: 100%"
              ref="adminMobile"
              label="手机号"
              name="adminMobile"
            >
              <a-input
                v-model:value="formState.adminMobile"
                placeholder="请输入手机号"
              />
            </a-form-item>
            <a-form-item
              style="width: 100%"
              ref="smsCode"
              label="验证码"
              name="smsCode"
            >
              <a-input
                v-model:value="formState.smsCode"
                placeholder="请输入验证码"
              >
                <template #suffix> 
                  <span @click="getCode" style="cursor:pointer;color: #34bbff;">
                     {{showTime?`${timer}s重新获取验证码`:'获取验证码'}}
                    </span> </template>
              </a-input>
            </a-form-item>
            <a-form-item
              style="width: 100%"
              ref="password"
              label="登录密码"
              name="password"
            >
              <a-input-password
                v-model:value="formState.password"
                placeholder="请输入登录密码"
              />
            </a-form-item>
            <div class="sub-title mt29 mb30">单位信息</div>
            <a-form-item
              ref="name"
              label="单位名称"
              name="name"
               style="width: 100%;"
            >
              <a-input
                v-model:value="formState.name"
                placeholder="请输入单位名称"
              />
            </a-form-item>
            <a-form-item
              style="width: 100%;"
              ref="shortName"
              label="简称"
              name="shortName"
            >
              <a-input
                v-model:value="formState.shortName"
                placeholder="请输入简称"
              />
            </a-form-item>
            <a-form-item
              style="width: 100%;"
              ref="code"
              label="医疗机构编码"
              name="code"
            >
              <a-input
                v-model:value="formState.code"
                placeholder="请输入医疗机构编码"
              />
            </a-form-item>
            <a-form-item
               style="width: 100%;"
              ref="code"
              label="医疗机构编号"
              name="num"
            >
              <a-input
                disabled
                v-model:value="formState.num"
                placeholder="系统自动生成"
              />
            </a-form-item>
            <a-form-item
              style="width: 100%;"
              ref="creditCode"
              label="企业信用代码"
              name="creditCode"
            >
              <a-input
                v-model:value="formState.creditCode"
                placeholder="请输入企业信用代码"
              />
            </a-form-item>
            <a-form-item
              style="width: 100%;"
              ref="addressCode"
              label="省市区"
              name="addressCode"
            >
              <a-cascader
                v-model:value="formState.addressCode"
                :options="treeData"
                :loadData="loadData"
                change-on-select
                placeholder="请选择省市区"
              >
              </a-cascader>
            </a-form-item>
            <a-form-item
              style="width: 100%;"
              ref="address"
              label="详细地址"
              name="address"
            >
              <a-input
                v-model:value="formState.address"
                placeholder="请输入详细地址"
              />
            </a-form-item>
            <a-form-item
              style="width: 100%"
              label="经度-纬度"
            >
              <a-input
                style="width: 140px"
                v-model:value="formState.longitude"
                placeholder="经度"
              />
               <a-input
                style="width: 140px"
                v-model:value="formState.latitude"
                placeholder="纬度"
              />
              <a-button type="link" @click="handleInnerVisible">
                <template #icon>
                  <EnvironmentTwoTone />
                </template>
                地图定位</a-button
              >
            </a-form-item>
            <a-form-item style="width:100%;margin-left:150px"  >
 <a-button type="primary"  block @click="handleOk">提交申请</a-button>
            </a-form-item>
          </a-form>
         
           <a-modal
      width="40%"
      v-model:visible="innerVisible"
      title="坐标位置"
      ok-text="确认"
      cancel-text="取消"
      @ok="handleSaveBmap"
    >
      <BMap class="h390" ref="bmap"></BMap>
    </a-modal>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  toRaw,
  toRef,
  toRefs,
  watch,
} from "vue";
import * as userApi from "@/api/user";
import { EnvironmentTwoTone } from "@ant-design/icons-vue";
import BMap from "@/components/BMap/index.vue";
import TreeSelect from "@/components/TreeSelect";
import * as areaApi from "@/api/area";
import * as hospitalApi from "@/api/hospital";
import { message } from "ant-design-vue";
import { useRouter } from 'vue-router';
export default {
    components: {
    TreeSelect,
    BMap,
    EnvironmentTwoTone,
  },
  setup() {
      const router = useRouter()
     const validateUserPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入管理员电话"));
      } else if (value && !/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
        callback(new Error("电话有误，请重填"));
      } else {
        callback();
      }
    };
    const validateUserName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入管理员"));
      } else if (
        value &&
        !/^[A-Za-z0-9]{1,50}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,25}$/.test(value)
      ) {
        callback(new Error("管理员名称不超过50个英文字符或25个汉字"));
      } else {
        callback();
      }
    };

    const validatePwd = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else if (value.length < 6 || value.length > 12) {
        callback(new Error("请输入6-12位登录密码"));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      {
        if (!value) {
          callback(new Error("请输入医疗机构编码"));
        } else if (value.length > 22) {
          callback(new Error("医疗机构编码长度小于22位"));
        } else {
          callback();
        }
      }
    };
    const validateCreditCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入企业信用代码"));
      } else if (value.length > 22) {
        callback(new Error("企业信用代码长度小于22位"));
      } else {
        callback();
      }
    };
    const validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入单位名称"));
      } else if (
        value &&
        !/^[A-Za-z0-9]{1,100}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,50}$/.test(value)
      ) {
        callback(new Error("单位名称不超过100个英文字符或50个汉字"));
      } else {
        callback();
      }
    };
    const validateshortName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入简称"));
      } else if (
        value &&
        !/^[A-Za-z0-9]{1,50}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,25}$/.test(value)
      ) {
        callback(new Error("简称不超过50个英文字符或25个汉字"));
      } else {
        callback();
      }
    };
    const validateAddress = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入详细地址"));
      } else if (value && !/^[A-Za-z0-9]{1,100}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,50}$/.test(value)) {
        callback(new Error("详细地址不超过100个英文字符或者50个汉字"));
      } else {
        callback();
      }
    }
    const rules = {
        name: [
          {
            required: true,
            validator: validateName,
            trigger: "blur",
          },
        ],
        shortName: [
          {
            required: true,
            validator: validateshortName,
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            validator: validateCode,
            trigger: "blur",
          },
        ],
        creditCode: [
          {
            required: true,
            validator: validateCreditCode,
             trigger: "blur",
          },
        ],
        addressCode: [
          {
            required: true,
            message: "请选择省市区",
          },
        ],
        address: [
          {
            required: true,
            validator: validateAddress,
            trigger: "blur",
          },
        ],
        adminName: [
          {
            required: true,
            validator: validateUserName,
            trigger: "blur",
          },
        ],
        adminMobile: [
          {
            required: true,
            validator: validateUserPhone,
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            validator: validatePwd,
            trigger: "blur",
          },
        ],
        smsCode: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur",
          },
        ],
      }
    const formRef = ref();
    const formState = reactive({
      address: "", //详细地址
      shortName: "",
      adminMobile: "", //管理员电话
      adminName: "", //管理员名称
      cityCode: "", //市编码
      code: "", //医院编码
      creditCode: "", //信用代码
      id: "",
      adminId: "",
      addressCode: [],
      isFreeze: 1,
      name: "", //医院名称
      provinceCode: "", //省编码
      regionCode: "", //区编码
      townCode: "", //镇编码
      password: "", //登入密码
      smsCode: "", //验证码
    });
 // 省市区
    const _shq = reactive({
      treeData: [
        {
          value: "zhejiang",
          label: "Zhejiang",
          isLeaf: false,
        },
        {
          value: "jiangsu",
          label: "Jiangsu",
          isLeaf: false,
        },
      ],
    });
    // 获取省
    const getS_ = async () => {
      const { data } = await areaApi.getProvinceList();
      _shq.treeData = data.map((item) => {
        return {
          label: item.name,
          value: item.code,
          isLeaf: false,
          type: "provice",
        };
      });
    };

    // 动态获取下一级
    const loadData = (selectedOptions) => {
      console.log(1222);
      console.log(selectedOptions);
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true; // load options lazily

      setTimeout(async () => {
        targetOption.loading = false;
        let res = [];
        if (targetOption.type == "provice") {
          res = await areaApi.getCityList({
            provinceCode: targetOption.value,
          });
          targetOption.children = res.data.map((item) => {
            return {
              label: item.name,
              value: item.code,
              isLeaf: false,
              type: "city",
            };
          });
        } else if (targetOption.type == "city") {
          res = await areaApi.getRegionList({
            cityCode: targetOption.value,
          });
          targetOption.children = res.data.map((item) => {
            return {
              label: item.name,
              value: item.code,
              isLeaf: false,
              type: "region",
            };
          });
        } else if (targetOption.type == "region") {
          res = await areaApi.getTownList({
            regionCode: targetOption.value,
          });
          targetOption.children = res.data.map((item) => {
            return {
              label: item.name,
              value: item.code,
              isLeaf: true,
              type: "town",
            };
          });
        }

        _shq.treeData = [..._shq.treeData];
      }, 1000);
    };
    // 地图
    const bmap = ref(null);
    const innerVisible = ref(false);
    // 打开地图
    const handleInnerVisible = () => {
      innerVisible.value = true;
    };
    //获取地图数据
    const handleSaveBmap = (row) => {
      formState.longitude = bmap.value.form.longitude;
      formState.latitude = bmap.value.form.latitude;
      formState.address = bmap.value.form.address;
      innerVisible.value = false;
    };
    const backLogin = ()=>{
      router.go(-1)
    }

    const handleOk = ()=>{
       formRef.value.validate().then(() => {
         if(!formState.longitude || !formState.latitude){
           message.warning('请地图定位')
           return false
         }
          let params = {
            address: formState.address, //详细地址
            shortName: formState.shortName,
            adminMobile: formState.adminMobile, //管理员电话
            adminName: formState.adminName, //管理员名称
            cityCode: formState.addressCode[1], //市编码
            code: formState.code, //医院编码
            creditCode: formState.creditCode,
            id: formState.id,
            adminId: formState.adminId,
            isFreeze: formState.isFreeze,
            name: formState.name, //医院名称
            provinceCode: formState.addressCode[0], //省编码
            regionCode: formState.addressCode[2], //区编码
            townCode: formState.addressCode[3], //镇编码
            smsCode: formState.smsCode, //验证码
            password: formState.password, //登入密码
            longitude: formState.longitude,
            latitude: formState.latitude,
          };
          userApi.hospitalBaseRegister(params).then((res) => {
            if (res && res.success) {
               router.push({ path: '/login' });
              message.success('后台审核中...,请稍等..')
            }
          });
       })
      
    }
    // 获取验证码
    const showTime = ref(false)
    const timer = ref(60)
     const  getCode = ()=>{
      if(showTime.value) {
        return
      }
      if (!formState.adminMobile) {
         message.error('请输入手机号')
        return;
      } else if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(formState.adminMobile)) {
     
        message.error('电话有误，请重填')
        return;
      }
      timer.value = 60;
      showTime.value = true;
      let timertime = null;
      if (timertime) {
        clearInterval(timertime);
      }
      userApi.sendMessage({ phone: formState.adminMobile }).then((res) => {
        if (res && res.success) {
          timertime = setInterval(() => {
            if ( timer.value  <= 0) {
              showTime.value = false;
              clearInterval(timertime);
            } else {
              timer.value--;
            }
          }, 1000);
        }
      });
    }
    onMounted(async ()=>{
       await getS_();
    })
    return {
      formRef,
      router,
      rules,
      wrapperCol: {
        span: 16,
      },
      labelCol: {
        style: {
          width: "150px",
        },
      },
      formState,
 ...toRefs(_shq),
       getS_,
      loadData,

      handleInnerVisible,
      innerVisible,
      handleSaveBmap,
      bmap,

      getCode,
      showTime,
      timer,

      handleOk,
      backLogin

    };
  },
};
</script>
<style lang="scss" scoped>
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}
/* reset element-ui css */
.login-container {
  .el-tabs__item {
    color: #fff;
  }
  .el-input {
    display: inline-block;
    // height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .el-form-item {
    margin-bottom: 24px;
    position: relative;
  }
  .el-form-item-1 {
    border: 1px solid #d7dadb;
    background: #fff;
    border-radius: 2px;
    height: 40px;
    line-height: 40px;
    color: #a5a7a8;
  }
  .login-form-content {
    width: 800px;
    min-height: 560px;
    display: flex;
    margin: 0 auto;
    padding: 45px 0;
    align-items: center;
    .login-bg {
      width: 800px;
      background: #fff;
      padding: 40px;
      border-radius: 8px;
    }
  }
}
</style>

<style lang="scss" scoped>
.demo-ruleForm {
  margin: 0 auto;
}
$bg: #34bbff;
$dark_gray: #333;
$light_gray: #333;
.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  background: url("../../assets/bg.png") center center no-repeat;
  background-size: cover;
  overflow: hidden;
  display: flex;
  align-items: center;

  .login-form {
    position: relative;
    max-width: 100%;
    overflow: hidden;
    box-sizing: border-box;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
    height: 40px;
    line-height: 40px;
    box-sizing: border-box;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 30px;
      color: $light_gray;
      text-align: center;
      font-weight: bold;
      margin-top: 52px;
    }
    .titleEn {
      font-size: 12px;
      color: $light_gray;
      margin: 10px 0;
      text-align: center;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .show-pwd-code {
    position: absolute;
    right: 10px;
    font-size: 16px;
    color: #34bbff;
    cursor: pointer;
    user-select: none;
  }
}
.form-rright {
  background: #fff;
  margin: 10px 0;
  color: $light_gray !important;
  flex-direction: column;
  padding: 0 70px;
  box-sizing: border-box;
  width: 440px;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
}
.el-tabs {
  width: 100%;
  ::v-deep .el-tabs__nav {
    width: 100%;
  }
  ::v-deep .el-tabs__item {
    width: 50% !important;
    color: #a5a7a8 !important;
    padding: 0;
    font-size: 16px;
    text-align: center;
  }
  ::v-deep .el-tabs__active-bar {
    width: 50% !important;
    background: #34bbff;
  }
  ::v-deep .is-active {
    color: #34bbff !important;
  }
  ::v-deep .el-form-item__content {
    height: 38px;
    line-height: 38px;
  }
  ::v-deep .el-input {
    height: 38px;
    line-height: 38px;
    input {
      height: 38px;
      line-height: 38px;
      box-sizing: border-box;
      color: #a5a7a8;
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px #fff inset !important;
        -webkit-text-fill-color: #7c7e82 !important;
      }
    }
  }
  .svg-icon {
    vertical-align: 0.35em;
  }
}
.color-gray {
  color: #a5a7a8 !important;
}
::v-deep .el-tabs__header {
  margin-bottom: 30px;
}
.title {
  font-weight: bold;
  color: #333;
}
.back {
  font-size: 14px;
  color: #a5a7a8;
}
.sub-title {
  font-size: 16px;
  color: #333;
}
</style>
